package com.example.prom.ok.y2022.controller.email.sendgrid.controller;

import com.alibaba.fastjson.JSON;
import com.example.prom.ok.y2022.controller.email.sendgrid.handler.EventWebhook;
import com.example.prom.ok.y2022.controller.email.sendgrid.model.CallbackModel;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
import java.security.SignatureException;
import java.security.interfaces.ECPublicKey;
import java.security.spec.InvalidKeySpecException;
import java.util.List;

@RestController
@RequestMapping("sendgrid/mail")
public class CallbackController {


    @PostMapping("callback")
    public void test(HttpServletRequest request, @RequestBody byte[] bytes){
        String pubKey = "MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEa/BI4UFZsSEiJIeb1alUBjpgRJnz3MWfQ3rnxNc0YwldsCBZqGZ8YCPhHL/upiXPwoEerUbtHVcMRHJ1BLHk+A==";
        String signature = request.getHeader("X-Twilio-Email-Event-Webhook-Signature");
        String timestamp = request.getHeader("x-twilio-email-event-webhook-timestamp");

//        System.out.println(JSON.parse(bytes));
        String s = new String(bytes);
        System.out.println(s);
        List<CallbackModel> callbackModels = JSON.parseArray(s, CallbackModel.class);
        System.out.println(JSON.toJSONString(callbackModels));

        System.out.println(signature);
        System.out.println(timestamp);
        try {
            EventWebhook eventWebhook = new EventWebhook();
            ECPublicKey ecPublicKey = eventWebhook.ConvertPublicKeyToECDSA(pubKey);
            boolean b = false;
            try {
                b = eventWebhook.VerifySignature(ecPublicKey, bytes, signature, timestamp);
            } catch (InvalidKeyException e) {
                e.printStackTrace();
            } catch (SignatureException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
            System.out.println("验签结果："+b);
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (NoSuchProviderException e) {
            e.printStackTrace();
        } catch (InvalidKeySpecException e) {
            e.printStackTrace();
        }
    }


}
